package com.liushuai.eas.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.Course;
import com.liushuai.eas.pojo.Department;
import com.liushuai.eas.service.CategoryImp;
import com.liushuai.eas.service.CourseImp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Resource
    private CourseImp courseImp;

    @Resource
    private CategoryImp categoryImp;

    @PostMapping
    public Result<?> add(@RequestBody Course course){

        //插入course数据库
        if (courseImp.insert(course)!=1)
            return Result.fail(course);

        return Result.success(course);
    }

    @PutMapping
    public Result<Course> update(@RequestBody Course course){
        if (courseImp.updateById(course)!=1)
            return Result.fail(course);
        return Result.success(course);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        List<Course> courseList;
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();

        if (search.isEmpty()){
            courseList = courseImp.queryCourseList((pageNum - 1) * pageSize,  pageSize);
            total = courseImp.queryTotal();
        }else {
            courseList = courseImp.queryCourseListBySearch((pageNum - 1) * pageSize, pageSize,search);
            total = courseImp.queryTotalBySearch(search);
        }

        for(Course course : courseList){
            course.setCategory(categoryImp.selectOne(course.getCategoryId()));
        }

        map.put("records",courseList);
        map.put("total",total);
        map.put("pageSize",pageSize);
        return Result.success("数据加载成功",map);
    }

    @DeleteMapping
    public Result<Course> delete(@RequestBody Course course){
        if (courseImp.deleteById(course)!=1)
            return Result.fail(course);
        return Result.success(course);
    }

    @GetMapping("/selectAll")
    public Result<List<Course>> selectAll(){

        List<Course> courseList = courseImp.selectList(new QueryWrapper<>());

        return Result.success(courseList);
    }

    @PostMapping("/queryCourseById")
    public Result<Course> queryCourseById(@RequestBody Map<String,Integer> map){

        Integer courseId = map.get("courseId");

        Course course = courseImp.selectOne(courseId);

        return Result.success(course);
    }

}
